<template>
  <n-dropdown :options="options" @select="handleSelect" trigger="hover">
    <div class="user-info">
      <n-avatar
        round
        :size="32"
        :src="user.avatar || '/avatar.png'"
      />
      <span class="username">{{ user.phone}}</span>
      <n-icon size="14" class="arrow-icon">
        <DownOutlined />
      </n-icon>
    </div>
  </n-dropdown>
</template>

<script setup>
import { h } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { NIcon, NAvatar } from 'naive-ui'
import {
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  DownOutlined
} from '@vicons/antd'
const user = JSON.parse(localStorage.getItem('user') || '{}')
const router = useRouter()
const userStore = useUserStore()

const options = [
  {
    label: '个人中心',
    key: 'profile',
    icon: renderIcon(UserOutlined)
  },

  {
    type: 'divider'
  },
  {
    label: '退出登录',
    key: 'logout',
    icon: renderIcon(LogoutOutlined)
  }
]

function renderIcon(icon) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

const handleSelect = (key) => {
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}
</script>

<style lang="scss" scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  color: white;
  &:hover {
    background: var(--bg-hover);
  }

  .username {
    font-size: 14px; 
    white-space: nowrap;
    margin: 0 4px;
  }

  .arrow-icon { 
    margin-left: 4px;
  }
}

:deep(.n-dropdown-menu) {
  min-width: 120px;

  .n-dropdown-option {
    padding: 8px 12px;

    &:hover {
      background: var(--primary-bg);
      color: var(--primary-color);
    }

    .n-dropdown-option-icon {
      margin-right: 8px;
    }
  }
}
</style>
